﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Globalization;

namespace GWA.Controls
{
    public partial class LoginPanel : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.User.Identity.IsAuthenticated)
                HelloUser();            
        }

        protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
        {
            Login Login1 = (Login)LoginView1.FindControl("Login1");
            
            if (Membership.ValidateUser(Login1.UserName, Login1.Password))
            {
                FormsAuthentication.SetAuthCookie(Login1.UserName, Login1.RememberMeSet);
                Response.Redirect(AccessPage(Login1.UserName));
            }
        }

        protected void LoginStatus1_LoggedOut(Object sender, EventArgs e)
        {
            Response.Redirect("~/Default.aspx");
        }

        protected void Login1_Error(object sender, EventArgs e)
        {
            Login Login1 = (Login)LoginView1.FindControl("Login1");
            Login1.FailureText = "Login Failed, Please try again";
        }

        private void HelloUser()
        {
            Label lblUsername = (Label)LoginView2.FindControl("lblUsername");
            lblUsername.Text = "Hello, " + CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Page.User.Identity.Name.ToString());
        }

        public static string AccessPage(string Username)
        {
            string[] role = Roles.GetRolesForUser(Username);
            switch (role[0].ToString())
            {
                case "Administrator":
                    return "~/Admin/Administrator.aspx";
                case "Doctor":
                    return "~/Doctor/doctor.aspx";
                case "Patient":
                    return "~/Patients/patients.aspx";
            }

            return null;
        }

        protected void btnRegister_Click(object sender, EventArgs e)
        {
            TextBox name = (TextBox)LoginView1.FindControl("txtRegName");
            TextBox email = (TextBox)LoginView1.FindControl("txtRegEmail");
            Response.Redirect("~/register.aspx?name=" + name.Text + "&email=" + email.Text);
        }
    }
}